<template>
  <div>
    <div v-for="(tabField, key) in tabFields" :key="key" style="display: flex; margin-bottom: 5px">
      <el-input v-model="tabField.label" style="width: 150px" />
      <el-select v-model="tabField.fields" placeholder="请选择" multiple style="width: 100%; margin: 0 10px">
        <el-option v-for="item in processedFieldItemsOption" :key="item.value" :label="item.label" :value="item.value"
          :disabled="item.disabled" />
      </el-select>
      <el-button type="" :icon="Delete" plain size="small" style="height: 30px" @click="delTab(key)" />
    </div>
    <el-button style="width: 100%" @click="addTab()">
      <el-icon>
        <Plus />
      </el-icon> {{ addText }}</el-button>
  </div>
</template>
<script>
import { Delete, Plus } from '@element-plus/icons-vue'

export default {
  name: 'FormTabForm',
  components: {
    Delete,
    Plus
  },
  props: {
    addText: {
      default: '添加选项卡',
      type: String
    },
    defaultLabel: {
      default: '新选项',
      type: String
    },
    modelValue: {
      default: () => {
        return []
      },
      type: Array
    },
    fieldItemsOption: {
      default: () => {
        return []
      },
      type: Array
    }
  },
  emits: ['update:modelValue'],
  data() {
    return {
      tabFields: [],
      Delete,
      Plus
    }
  },
  computed: {
    processedFieldItemsOption() {
      return this._fieldItemsOption()
    }
  },
  watch: {
    modelValue: {
      handler(newVal) {
        // 避免无限循环，只在真正不同时更新
        if (JSON.stringify(newVal) !== JSON.stringify(this.tabFields)) {
          this.tabFields = JSON.parse(JSON.stringify(newVal || []))
        }
      },
      immediate: true,
      deep: true
    },
    tabFields: {
      handler(newVal) {
        this.$emit('update:modelValue', JSON.parse(JSON.stringify(newVal)))
      },
      deep: true
    }
  },
  methods: {
    addTab() {
      this.tabFields.push({ label: this.defaultLabel, fields: [] })
    },
    delTab(key) {
      this.tabFields.splice(key, 1)
    },
    _fieldItemsOption() {
      // 获取所有已存在的字段值
      const existingFields = this.tabFields.reduce((acc, tab) => {
        return acc.concat(tab.fields)
      }, [])

      // 更新 fieldItemsOption，标记已存在的字段为 disabled
      return this.fieldItemsOption.map((item) => ({
        ...item,
        disabled: existingFields.includes(item.value)
      }))
    }
  }
}
</script>

<style scoped lang="scss"></style>
